package com.sinog.front.util;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @desc POI导出工具类
 * @author qjwyss
 * @date 2018/9/18
 */
public class PoiUtil {

    /**
     * 下载EXCEL到本地指定的文件夹
     * @param wb EXCEL对象SXSSFWorkbook
     * @param exportPath 导出路径
     */
    public static void downLoadExcelToLocalPath(SXSSFWorkbook wb,String exportPath) {
        FileOutputStream fops = null;
        try {
            fops = new FileOutputStream(exportPath);
            wb.write(fops);
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(null != wb) {
                try {
                    wb.dispose();
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
            if(null != fops) {
                try {
                    fops.close();
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 下载EXCEL到浏览器
     * @param wb EXCEL对象XSSFWorkbook
     * @param response response
     * @param fileName 文件名称
     */
    public static void downLoadExcelToWebsite(SXSSFWorkbook wb,HttpServletResponse response,String fileName) throws IOException {
        //设置下载的文件名
        response.setHeader("Content-disposition","attachment; filename=" + new String((fileName + ".xlsx").getBytes(StandardCharsets.UTF_8),"ISO8859-1"));
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(null != wb) {
                try {
                    wb.dispose();
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
            if(null != outputStream) {
                try {
                    outputStream.close();
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}